/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.institution.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.koron.audit.management.FlowManagement;
import com.koron.common.Tools;
import com.koron.common.bean.DepartmentTreeBean;
import com.koron.common.bean.GroupBean;
import com.koron.common.bean.SecretBean;
import com.koron.common.bean.StaffBean;
import com.koron.common.dfs.FastDFSClientWrapper;
import com.koron.common.stub.Port;
import com.koron.common.util.DocConverterUtils;
import com.koron.common.web.Util;
import com.koron.institution.bean.InstitutionCategory;
import com.koron.institution.bean.InstitutionFile;
import com.koron.institution.mapper.InstitutionCategoryMapper;
import com.koron.institution.mapper.InstitutionFileMapper;
import com.koron.institution.service.api.CategoryService;
import com.koron.institution.uitls.BaseEntityUtil;
import com.koron.institution.uitls.BusinessCode;
import com.koron.risk.bean.CorpBean;
import com.koron.risk.service.api.CorpManagementService;
import com.koron.system.domain.DictData;
import com.koron.system.domain.DictType;
import com.koron.system.service.api.DictTypeService;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl implements CategoryService {

    private final static  Logger logger = LoggerFactory.getLogger(Logger.class);

    @Autowired
    private FlowManagement flowManagement;

    @Autowired
    private DictTypeService dictTypeService;

    @Autowired
    private FastDFSClientWrapper clientWrapper;

    @Autowired
    private DocConverterUtils docConverterUtils;

    @Autowired
    private CorpManagementService corpService;

    @Autowired
    private Util util;

    @Value("${app.appid}")
    private String appid;

    @Value("${app.secret}")
    private String secret;

    @Value("${app.orgCode}")
    private String orgCode;


    private List<Map<String, String>> corpCodeMap;

    @Override
    public MessageBean<?> getCategoryList(String corpCode, Integer institutionType) {
        MessageBean<List> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), List.class);
        try (SessionFactory factory = new SessionFactory()) {
            if (institutionType == null) {
                msg.setCode(BusinessCode.EMPTY_INSTITUTION_TYPE.getCode());
                msg.setDescription(BusinessCode.EMPTY_INSTITUTION_TYPE.getDescription());
                return msg;
            }
            if (institutionType != 1) {
                if (StringUtils.isBlank(corpCode)) {
                    msg.setCode(BusinessCode.EMPTY_CATEGORY_CORPCODE.getCode());
                    msg.setDescription(BusinessCode.EMPTY_CATEGORY_CORPCODE.getDescription());
                    return msg;
                }
            }
            InstitutionCategoryMapper mapper = factory.getMapper(InstitutionCategoryMapper.class);
            List<InstitutionCategory> categoryList = mapper.getCategoryList(corpCode, institutionType);
            List<InstitutionCategory> treeList = new ArrayList<>();
            if (categoryList != null && !categoryList.isEmpty()) {
                categoryList.stream().forEach(bean -> {
                    Integer count = factory.getMapper(InstitutionFileMapper.class).countInstitutionByCategoryId(bean.getId());
                    if (count > 0) {
                        bean.setFileExist(true);
                    }
                });
                treeList = categoryList.stream().filter(category -> "root".equalsIgnoreCase(category.getPid())).collect(Collectors.toList());
                createTree(treeList, categoryList);
            }
            msg.setData(treeList);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<?> getCategoryLists(String corpCode, StaffBean user, Integer institutionType) {
        MessageBean<Map> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Map.class);
        try (SessionFactory factory = new SessionFactory()) {
            if (institutionType == null) {
                msg.setCode(BusinessCode.EMPTY_INSTITUTION_TYPE.getCode());
                msg.setDescription(BusinessCode.EMPTY_INSTITUTION_TYPE.getDescription());
                return msg;
            }
            if (institutionType != 1) {
                if (StringUtils.isBlank(corpCode)) {
                    msg.setCode(BusinessCode.EMPTY_CATEGORY_CORPCODE.getCode());
                    msg.setDescription(BusinessCode.EMPTY_CATEGORY_CORPCODE.getDescription());
                    return msg;
                }
            }
            // 获取当前登陆人公司权限
            String userOperationCorp = getUserOperationCorp(user);
//            String userCorp = getUserCorp(user);
            InstitutionCategoryMapper mapper = factory.getMapper(InstitutionCategoryMapper.class);
            List<Map> mapList = new ArrayList<>();
            Map result = new HashMap();
            if (institutionType == 2) {
                // 如果是集团人员，可以看到全部数据
                if (("776B361BFFAC4F00BBF459CD1303A8B2").equals(userOperationCorp)) {
                    if (null == corpCodeMap || corpCodeMap.size() <= 0) {
                        getCorpCodeMap();
                    }
                    corpCodeMap.stream().forEach(map -> {
                        if (!("776B361BFFAC4F00BBF459CD1303A8B2").equals(map.get("corpCode"))) {
                            Map map1 = new HashMap();
                            List<Map> categoryMap = new ArrayList<>();
                            // 获取集团制度
                            List<InstitutionCategory> list = mapper.getCategoryList(null, 1);
                            // 获取公司下的制度
                            List<InstitutionCategory> categoryList = mapper.getCategoryList(map.get("corpCode"), institutionType);
                            // 处理集团的制度
                            if (null != list && list.size() > 0) {
                                list.stream().forEach(bean -> {
                                    List<InstitutionFile> institutionFiles = factory.getMapper(InstitutionFileMapper.class).getInstitution(bean.getId(), map.get("corpCode"));
                                    Map institutionMap = new HashMap();
                                    if (institutionFiles.size() > 0) {
                                        InstitutionFile institutionFile = institutionFiles.get(0);
                                        institutionMap.put("fileExist", true);
                                        institutionMap.put("attachment", institutionFile.getAttachment());
                                        institutionMap.put("previewAttachment", institutionFile.getPreviewAttachment());
                                        institutionMap.put("institutionId", institutionFile.getId());
                                    } else {
                                        institutionMap.put("fileExist", false);
                                    }
                                    setMap(bean, institutionMap, institutionType);
                                    categoryMap.add(institutionMap);
                                });
                            }
                            // 处理公司自己的制度
                            if (categoryList != null && !categoryList.isEmpty()) {
                                categoryList.stream().forEach(bean -> {
                                    List<InstitutionFile> institutionFiles = factory.getMapper(InstitutionFileMapper.class).getInstitution(bean.getId(), map.get("corpCode"));
                                    Map institutionMap = new HashMap();
                                    if (institutionFiles.size() > 0) {
                                        institutionMap.put("fileExist", true);
                                        InstitutionFile institutionFile = institutionFiles.get(0);
                                        institutionMap.put("attachment", institutionFile.getAttachment());
                                        institutionMap.put("previewAttachment", institutionFile.getPreviewAttachment());
                                        institutionMap.put("institutionId", institutionFile.getId());
                                    } else {
                                        institutionMap.put("fileExist", false);
                                    }
                                    setMap(bean, institutionMap, institutionType);
                                    categoryMap.add(institutionMap);
                                });
                            }
                            map1.put("corpCode", map.get("corpCode"));
                            map1.put("corpName", map.get("corpName"));
                            map1.put("categoryList", categoryMap);
                            mapList.add(map1);
                            result.put("isGroup", true);
                            result.put("data", mapList);
                        }
                    });
                    msg.setData(result);
                } else {
                    List<Map> categoryMap = new ArrayList<>();
                    // 获取集团制度
                    List<InstitutionCategory> list = mapper.getCategoryList(null, 1);
                    if (null != list && list.size() > 0) {
                        list.stream().forEach(bean -> {
                            List<InstitutionFile> institutionFiles = factory.getMapper(InstitutionFileMapper.class).getInstitution(bean.getId(), userOperationCorp);
                            Map institutionMap = new HashMap();
                            if (institutionFiles.size() > 0) {
                                institutionMap.put("fileExist", true);
                                InstitutionFile institutionFile = institutionFiles.get(0);
                                institutionMap.put("attachment", institutionFile.getAttachment());
                                institutionMap.put("previewAttachment", institutionFile.getPreviewAttachment());
                                institutionMap.put("institutionId", institutionFile.getId());
                            } else {
                                institutionMap.put("fileExist", false);
                            }
                            setCorpMap(bean, institutionMap, institutionType, userOperationCorp);
                            institutionMap.put("edit", false);
                            categoryMap.add(institutionMap);
                        });
                    }
                    // 获取公司制度
                    List<InstitutionCategory> categoryList = mapper.getCategoryList(userOperationCorp, institutionType);
                    if (categoryList != null && !categoryList.isEmpty()) {
                        categoryList.stream().forEach(bean -> {
                            List<InstitutionFile> institutionFiles = factory.getMapper(InstitutionFileMapper.class).getInstitution(bean.getId(), userOperationCorp);
                            Map map = new HashMap();
                            if (institutionFiles.size() > 0) {
                                map.put("fileExist", true);
                                InstitutionFile institutionFile = institutionFiles.get(0);
                                map.put("attachment", institutionFile.getAttachment());
                                map.put("previewAttachment", institutionFile.getPreviewAttachment());
                                map.put("institutionId", institutionFile.getId());
                            } else {
                                map.put("fileExist", false);
                            }
                            setMap(bean, map, institutionType);
                            map.put("edit", true);
                            categoryMap.add(map);
                        });
                    }
                    result.put("isGroup", false);
                    result.put("corpCode", userOperationCorp);
                    result.put("categoryList", categoryMap);
                    msg.setData(result);
                }
            } else {
                List<Map> categoryMap = new ArrayList<>();
                List<InstitutionCategory> categoryList = mapper.getCategoryList(userOperationCorp, institutionType);
                if (categoryList != null && !categoryList.isEmpty()) {
                    categoryList.stream().forEach(bean -> {
                        List<InstitutionFile> institutionFiles = factory.getMapper(InstitutionFileMapper.class).queryInstitutionByCategoryId(bean.getId());
                        Map map = new HashMap();
                        if (institutionFiles.size() > 0) {
                            map.put("fileExist", true);
                            InstitutionFile institutionFile = institutionFiles.get(0);
                            map.put("attachment", institutionFile.getAttachment());
                            map.put("previewAttachment", institutionFile.getPreviewAttachment());
                            map.put("institutionId", institutionFile.getId());
                        } else {
                            map.put("fileExist", false);
                        }
                        setMap(bean, map, institutionType);
                        categoryMap.add(map);
                    });
                }
                result.put("isGroup", false);
                result.put("categoryList", categoryMap);
                msg.setData(result);
            }
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
    }

    // 获取用户权限公司所属公司
    private String getUserOperationCorp(StaffBean user) {
        // 获取用户权限公司
        //已开通的公司列表
        List<CorpBean> corpBeanList = corpService.corpBeanList();
        if (null != corpBeanList) {
            Map<String, CorpBean> corpMap = corpBeanList.stream().collect(Collectors.toMap(CorpBean::getCorpCode, corp -> corp, (v1, v2) -> v2));
            LinkedHashSet<String> codeSet = new LinkedHashSet<String>();
            //是否放入默认公司
            SecretBean secretBean = new SecretBean();
            secretBean.setAppid(appid);
            secretBean.setSecret(secret);
            Port port = new Port(secretBean);
            //获取群组列表
            MessageBean<Map> groupMap = port.getRolesAndGroupsByStaff(user.getCode(), 512);
            Map map = groupMap.getData();
            if (map != null) {
                List<GroupBean> groutList = (List<GroupBean>) map.get("group");
                if (groutList != null) {
                    List<String> attrList = groutList.stream().map(GroupBean::getAttr).collect(Collectors.toList());
                    //从群组的attr属性中取出已分配的corpCode
                    for (String attr : attrList) {
                        Map<String, String> attrMap = (Map<String, String>) JSON.parse(attr);
                        if (attrMap != null) {
                            String corpCode = attrMap.get("corpCode");
                            if (corpCode != null) {
                                String[] codeArray = corpCode.split(",");
                                for (String str : codeArray) {
                                    codeSet.add(str);
                                }
                            }
                        }
                    }
                }
            }
            List<CorpBean> result = new ArrayList<CorpBean>();
            for (String str : codeSet) {
                if (corpMap.keySet().contains(str)) {
                    result.add(corpMap.get(str));
                }
            }
            // 判断权限公司是否属于八个公司，不是则找其上级
            if (null != result && result.size() > 0) {
                CorpBean corpBean = result.get(0);
                if (null == corpCodeMap || corpCodeMap.size() <= 0) {
                    getCorpCodeMap();
                }
                List<String> corpCodes = corpCodeMap.stream().map(c -> c.get("corpCode")).collect(Collectors.toList());
                if (corpCodes.contains(corpBean.getCorpCode())) {
                    return corpBean.getCorpCode();
                } else {
                    MessageBean<?> msg = util.depttree(corpBean.getCorpCode(), 0);
                    if (msg.getCode() == 0 && null != msg.getData()) {
                        DepartmentTreeBean departmentTreeBean = null;
                        List<DepartmentTreeBean> data = (List<DepartmentTreeBean>) msg.getData();
                        if (null != data && data.size() > 0) {
                            List<DepartmentTreeBean> collect = data.stream().filter(dept -> corpBean.getCorpCode().equals(dept.getDepartmentCode())).collect(Collectors.toList());
                            if (null != collect && collect.size() > 0) {
                                departmentTreeBean = collect.get(0);
                            }
                        }
                        if (null != departmentTreeBean) {
                            if (orgCode.equals(departmentTreeBean.getOrgCode())) {
                                msg = util.getParentDepts(departmentTreeBean.getDepartmentCode());
                                if (msg.getData() != null) {
                                    List<DepartmentTreeBean> depTreeList = (List<DepartmentTreeBean>) msg.getData();
                                    ListIterator li = depTreeList.listIterator(depTreeList.size());
                                    while (li.hasPrevious()) {
                                        DepartmentTreeBean bean = (DepartmentTreeBean) li.previous();
                                        if (corpCodes.contains(bean.getDepartmentCode())) {
                                            return bean.getDepartmentCode();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return null;
    }

    // 获取用户所属公司
    private String getUserCorp(StaffBean user) {
        // 判断当前用户所属部门是否属于八大公司或集团
        if (null == corpCodeMap || corpCodeMap.size() <= 0) {
            getCorpCodeMap();
        }
        List<String> corpCodes = corpCodeMap.stream().map(c -> c.get("corpCode")).collect(Collectors.toList());
        if (corpCodes.contains(user.getDepartmentCode())) {
            return user.getDepartmentCode();
        } else {
            // 不属于则找其上级，直到找到八大公司或集团为止
            MessageBean<?> msg = util.depttree(user.getDepartmentCode(), 0);
            if (msg.getCode() == 0 && null != msg.getData()) {
                DepartmentTreeBean departmentTreeBean = null;
                List<DepartmentTreeBean> data = (List<DepartmentTreeBean>) msg.getData();
                if (null != data && data.size() > 0) {
                    List<DepartmentTreeBean> collect = data.stream().filter(dept -> user.getDepartmentCode().equals(dept.getDepartmentCode())).collect(Collectors.toList());
                    if (null != collect && collect.size() > 0) {
                        departmentTreeBean = collect.get(0);
                    }
                }
                if (null != departmentTreeBean) {
                    if (orgCode.equals(departmentTreeBean.getOrgCode())) {
                        msg = util.getParentDepts(departmentTreeBean.getDepartmentCode());
                        if (msg.getData() != null) {
                            List<DepartmentTreeBean> depTreeList = (List<DepartmentTreeBean>) msg.getData();
                            ListIterator li = depTreeList.listIterator(depTreeList.size());
                            while (li.hasPrevious()) {
                                DepartmentTreeBean bean = (DepartmentTreeBean) li.previous();
                                if (corpCodes.contains(bean.getDepartmentCode())) {
                                    return bean.getDepartmentCode();
                                }
                            }
                        }
                    }
                }
            }
        }
        return null;
    }

    private void setMap(InstitutionCategory bean, Map map, Integer institutionType) {
        map.put("id", bean.getId());
        map.put("corpCode", bean.getCorpCode());
        map.put("categoryName", bean.getCategoryName());
//        map.put("fileExist", bean.getFileExist());
        map.put("pid", bean.getPid());
        map.put("institutionType", institutionType);
    }

    private void setCorpMap(InstitutionCategory bean, Map map, Integer institutionType, String userOperationCorp) {
        map.put("id", bean.getId());
        map.put("corpCode", userOperationCorp);
        map.put("categoryName", bean.getCategoryName());
//        map.put("fileExist", bean.getFileExist());
        map.put("pid", bean.getPid());
        map.put("institutionType", institutionType);
    }

    void createTree(List<InstitutionCategory> treeList, List<InstitutionCategory> list) {
        if (list == null || list.isEmpty() || treeList == null || treeList.isEmpty()) {
            return;
        }
        List<InstitutionCategory> childList = null;
        for (InstitutionCategory institutionCategory : treeList) {
            childList = list.stream().filter(category -> institutionCategory.getId().equals(category.getPid())).collect(Collectors.toList());
            createTree(childList, list);
            institutionCategory.setChildList(childList);
        }
    }

    @Override
    public MessageBean<?> addCategory(String categoryStr, StaffBean user, String institutionStr, String corpCode, MultipartFile[] file) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Object.class);
        SessionFactory factory = new SessionFactory();
        try {
            if (StringUtils.isEmpty(categoryStr)) {
                msg.setCode(BusinessCode.EMPTY_CATEGORY.getCode());
                msg.setDescription(BusinessCode.EMPTY_CATEGORY.getDescription());
                return msg;
            }
            InstitutionCategory category = JSONObject.parseObject(categoryStr, InstitutionCategory.class);
            if (null == category.getInstitutionType()) {
                msg.setCode(BusinessCode.EMPTY_CATEGORY_TYPE.getCode());
                msg.setDescription(BusinessCode.EMPTY_CATEGORY_TYPE.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(category.getCorpCode())) {
                // 判断当前用户所属部门是否属于八大公司或集团
                if (null == corpCodeMap || corpCodeMap.size() <= 0) {
                    getCorpCodeMap();
                }
                List<String> corpCodes = corpCodeMap.stream().map(c -> c.get("corpCode")).collect(Collectors.toList());
                if (!corpCodes.contains(corpCode)) {
                    MessageBean<?> messageBean = util.getParentDepts(corpCode);
                    if (messageBean.getData() != null) {
                        List<DepartmentTreeBean> depTreeList = (List<DepartmentTreeBean>) messageBean.getData();
                        ListIterator li = depTreeList.listIterator(depTreeList.size());
                        while (li.hasPrevious()) {
                            DepartmentTreeBean bean = (DepartmentTreeBean) li.previous();
                            if (corpCodes.contains(bean.getDepartmentCode())) {
                                corpCode =  bean.getDepartmentCode();
                                break;
                            }
                        }
                    }
                }
                category.setCorpCode(corpCode);
            }
            if (category.getInstitutionType() != 1 && StringUtils.isBlank(category.getCorpCode())) {
                msg.setCode(BusinessCode.EMPTY_CATEGORY_CORPCODE.getCode());
                msg.setDescription(BusinessCode.EMPTY_CATEGORY_CORPCODE.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(category.getCategoryName())) {
                msg.setCode(BusinessCode.EMPTY_CATEGORY_NAME.getCode());
                msg.setDescription(BusinessCode.EMPTY_CATEGORY_NAME.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(category.getPid())) {
                msg.setCode(BusinessCode.EMPTY_CATEGORY_PID.getCode());
                msg.setDescription(BusinessCode.EMPTY_CATEGORY_PID.getDescription());
                return msg;
            }
            InstitutionCategoryMapper mapper = factory.getMapper(InstitutionCategoryMapper.class);
            //校验是否已存在
            Integer checkExist = mapper.checkExist(category);
            if (checkExist > 0) {
                msg.setCode(BusinessCode.CATEGORY_EXIST.getCode());
                msg.setDescription(BusinessCode.CATEGORY_EXIST.getDescription());
                return msg;
            }
            List<InstitutionCategory> categoryList = new ArrayList<>();
            BaseEntityUtil.setAddBaseProperties(category, user);
            categoryList.add(category);
            // 如果是添加集团制度,对应的公司也需要
//            if (category.getInstitutionType() == 1) {
//                if (null == corpCodeMap || corpCodeMap.size() <= 0) {
//                    getCorpCodeMap();
//                }
//                if (null != corpCodeMap && corpCodeMap.size() > 0) {
//                    for (Map<String, String> map : corpCodeMap) {
//                        InstitutionCategory bean = new InstitutionCategory();
//                        BeanUtils.copyProperties(category, bean);
//                        bean.setInstitutionType(2);
//                        bean.setCorpCode(map.get("corpCode"));
//                        BaseEntityUtil.setAddBaseProperties(bean, user);
//                        categoryList.add(bean);
//                    }
//                }
//            }
            if (null != categoryList && categoryList.size() > 0) {
                Integer value = mapper.batchInsert(categoryList);
                if (value > 0) {
                    if (null != institutionStr) {
                        InstitutionFile institution = JSONObject.parseObject(institutionStr, InstitutionFile.class);
                        //保存附件；
                        List<String> keepAddressList = new ArrayList<>();
                        List<String> keepPreAddressList = new ArrayList<>();
                        String originalFilename = null;
                        if (file != null && file.length > 0) {
                            for (MultipartFile f : file) {
                                if (file != null) {
                                    originalFilename = f.getOriginalFilename();
                                    String url = clientWrapper.uploadFile(f);
                                    String filPath = url + "#" + originalFilename;
                                    keepAddressList.add(filPath);
                                    String pdfPath = docConverterUtils.converterUpdate(f);
                                    if (pdfPath != null) {
                                        keepPreAddressList.add(pdfPath);
                                    } else {
                                        keepPreAddressList.add(filPath);
                                    }
                                }
                            }
                        }
                        institution.setAttachment((keepAddressList == null || keepAddressList.size() <= 0) ? null : new Gson().toJson(keepAddressList));
                        institution.setPreviewAttachment((keepPreAddressList == null || keepPreAddressList.size() <= 0) ? null : new Gson().toJson(keepPreAddressList));
                        institution.setCode(Tools.getCode32());
                        institution.setCategoryId(category.getId());
                        institution.setFileName(StringUtils.isNoneEmpty(institution.getFileName()) ? institution.getFileName() : originalFilename);
                        institution.setInstitutionType(category.getInstitutionType());
                        institution.setCorpCode(category.getInstitutionType() == 1 ? null : StringUtils.isNotEmpty(category.getCorpCode()) ? category.getCorpCode() : corpCode);
                        BaseEntityUtil.setAddBaseProperties(institution, user);
                        factory.getMapper(InstitutionFileMapper.class).insert(institution);
                    } else {
                        if (null != file && file.length > 0) {
                            InstitutionFile institution = new InstitutionFile();
                            //保存附件；
                            List<String> keepAddressList = new ArrayList<>();
                            List<String> keepPreAddressList = new ArrayList<>();
                            String originalFilename = null;
                            if (file != null && file.length > 0) {
                                for (MultipartFile f : file) {
                                    if (file != null) {
                                        originalFilename = f.getOriginalFilename();
                                        String url = clientWrapper.uploadFile(f);
                                        String filPath = url + "#" + originalFilename;
                                        keepAddressList.add(filPath);
                                        String pdfPath = docConverterUtils.converterUpdate(f);
                                        if (pdfPath != null) {
                                            keepPreAddressList.add(pdfPath);
                                        } else {
                                            keepPreAddressList.add(filPath);
                                        }
                                    }
                                }
                            }
                            institution.setAttachment((keepAddressList == null || keepAddressList.size() <= 0) ? null : new Gson().toJson(keepAddressList));
                            institution.setPreviewAttachment((keepPreAddressList == null || keepPreAddressList.size() <= 0) ? null : new Gson().toJson(keepPreAddressList));
                            institution.setCode(Tools.getCode32());
                            institution.setCategoryId(category.getId());
                            institution.setFileName(StringUtils.isNoneEmpty(institution.getFileName()) ? institution.getFileName() : originalFilename);
                            institution.setInstitutionType(category.getInstitutionType());
                            institution.setCorpCode(category.getInstitutionType() == 1 ? null : category.getCorpCode());
                            BaseEntityUtil.setAddBaseProperties(institution, user);
                            factory.getMapper(InstitutionFileMapper.class).insert(institution);
                        }
                    }
                } else {
                    factory.close(false);
                    msg.setCode(BusinessCode.FAILURE.getCode());
                    msg.setDescription("保存失败");
                    return msg;
                }
            }
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            factory.close(false);
            return msg;
        } finally {
            if (factory != null) {
                factory.close();
            }
        }
    }

    public void getCorpCodeMap() {
        // 获取公司信息
        MessageBean<List<DictType>> dictMsg = dictTypeService.getDictTypesAndDictDatas("公司");
        if (null != dictMsg.getData()) {
            List<DictType> dictData = dictMsg.getData();
            if (null != dictData && dictData.size() > 0) {
                List<DictData> dataList = dictData.get(0).getDataList();
                corpCodeMap = dataList.stream().map(dict -> {
                    Map<String, String> map = new HashMap();
                    map.put("corpCode", dict.getDictValue());
                    map.put("corpName", dict.getDictLabel());
                    return map;
                }).collect(Collectors.toList());
            }
        }
    }

    @Override
    public MessageBean<?> delete(String categoryId, StaffBean user) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Object.class);
        try (SessionFactory factory = new SessionFactory()) {
            InstitutionCategoryMapper institutionCategoryMapper = factory.getMapper(InstitutionCategoryMapper.class);
            InstitutionFileMapper institutionFileMapper = factory.getMapper(InstitutionFileMapper.class);
            Integer count = institutionFileMapper.countInstitutionByCategoryId(categoryId);
            if (count > 1) {
                msg.setCode(BusinessCode.CATEGORY_EXIST_INSTITUTIONS.getCode());
                msg.setDescription("公司已在该目录下添加制度，无法删除");
                return msg;
            }
            institutionCategoryMapper.deleteByPrimaryKey(categoryId);
            institutionFileMapper.deleteByCategoryId(categoryId);
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<?> updateCategory(String categoryStr, StaffBean user, Boolean flag, String institutionId, String corpCode, MultipartFile[] file, String keepFiles, String keepPDFFiles, String delFiles, String delPDFFiles) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Object.class);
        SessionFactory factory = null;
        try {
            factory = new SessionFactory();
            InstitutionCategoryMapper institutionCategoryMapper = factory.getMapper(InstitutionCategoryMapper.class);
            if (StringUtils.isEmpty(categoryStr)) {
                msg.setCode(BusinessCode.EMPTY_CATEGORY.getCode());
                msg.setDescription(BusinessCode.EMPTY_CATEGORY.getDescription());
                return msg;
            }
            InstitutionCategory category = JSONObject.parseObject(categoryStr, InstitutionCategory.class);
            if (StringUtils.isEmpty(category.getId())) {
                msg.setCode(BusinessCode.EMPTY_CATEGORY_ID.getCode());
                msg.setDescription(BusinessCode.EMPTY_CATEGORY_ID.getDescription());
                return msg;
            }
            InstitutionCategory entity = institutionCategoryMapper.selectByPrimaryKey(category.getId());
            if (entity == null) {
                msg.setCode(BusinessCode.CATEGORY_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.CATEGORY_NOT_EXIST.getDescription());
                return msg;
            }
            if (null == category.getInstitutionType()) {
                msg.setCode(BusinessCode.EMPTY_CATEGORY_TYPE.getCode());
                msg.setDescription(BusinessCode.EMPTY_CATEGORY_TYPE.getDescription());
                return msg;
            }
            if (entity.getInstitutionType().equals(category.getInstitutionType())) {
                if (category.getInstitutionType() != 1 && StringUtils.isBlank(corpCode)) {
                    msg.setCode(BusinessCode.EMPTY_CATEGORY_CORPCODE.getCode());
                    msg.setDescription(BusinessCode.EMPTY_CATEGORY_CORPCODE.getDescription());
                    return msg;
                }
                if (StringUtils.isEmpty(category.getCategoryName())) {
                    msg.setCode(BusinessCode.EMPTY_CATEGORY_NAME.getCode());
                    msg.setDescription(BusinessCode.EMPTY_CATEGORY_NAME.getDescription());
                    return msg;
                }
                if (StringUtils.isEmpty(category.getPid())) {
                    msg.setCode(BusinessCode.EMPTY_CATEGORY_PID.getCode());
                    msg.setDescription(BusinessCode.EMPTY_CATEGORY_PID.getDescription());
                    return msg;
                }
                //校验是否已存在
                Integer checkExist = institutionCategoryMapper.checkExist(category);
                if (checkExist > 0) {
                    msg.setCode(BusinessCode.CATEGORY_EXIST.getCode());
                    msg.setDescription(BusinessCode.CATEGORY_EXIST.getDescription());
                    return msg;
                }
                BaseEntityUtil.setUpdateBaseProperties(category, user);
                Integer value = institutionCategoryMapper.updateByPrimaryKeySelective(category);
            }
            //保存附件；
            if (StringUtils.isNotEmpty(institutionId)) {
                InstitutionFile institution = factory.getMapper(InstitutionFileMapper.class).selectByPrimaryKey(institutionId);
                List<String> keepAddressList = new ArrayList<>();
                List<String> keepPreAddressList = new ArrayList<>();
                List<String> keepAddressList1 = new ArrayList<>();
                List<String> keepPreAddressList1 = new ArrayList<>();
//                if (StringUtils.isNotBlank(institution.getAttachment())) {
//                    List<String> list = JSONObject.parseArray(institution.getAttachment(), String.class);
//                    keepAddressList.addAll(list);
//                }
//                if (StringUtils.isNotBlank(institution.getPreviewAttachment())) {
//                    List<String> list = JSONObject.parseArray(institution.getPreviewAttachment(), String.class);
//                    keepPreAddressList.addAll(list);
//                }
                if (StringUtils.isNotBlank(delFiles)) {
                    List<String> list = Arrays.stream(delFiles.split("[;；]")).collect(Collectors.toList());
                    keepAddressList.addAll(list);
                }
                if (StringUtils.isNotBlank(delPDFFiles)) {
                    List<String> list = Arrays.stream(delPDFFiles.split("[;；]")).collect(Collectors.toList());
                    keepPreAddressList.addAll(list);
                }
                if (StringUtils.isNotBlank(keepFiles)) {
                    List<String> list = Arrays.stream(keepFiles.split("[;；]")).collect(Collectors.toList());
                    keepAddressList1.addAll(list);
                }
                if (StringUtils.isNotBlank(keepPDFFiles)) {
                    List<String> list = Arrays.stream(keepPDFFiles.split("[;；]")).collect(Collectors.toList());
                    keepPreAddressList1.addAll(list);
                }
                String originalFilename = null;
                if (file != null && file.length > 0) {
                    for (MultipartFile f : file) {
                        if (file != null) {
                            originalFilename = f.getOriginalFilename();
                            String url = clientWrapper.uploadFile(f);
                            String filPath = url + "#" + originalFilename;
                            keepAddressList1.add(filPath);
                            String pdfPath = docConverterUtils.converterUpdate(f);
                            if (pdfPath != null) {
                                keepPreAddressList1.add(pdfPath);
                            } else {
                                keepPreAddressList1.add(filPath);
                            }
                        }
                    }
                }
                institution.setAttachment((keepAddressList1 == null) ? flag ? null : new Gson().toJson(keepAddressList) : new Gson().toJson(keepAddressList1));
                institution.setPreviewAttachment((keepPreAddressList1 == null) ? flag ? null : new Gson().toJson(keepPreAddressList) : new Gson().toJson(keepPreAddressList1));
                BaseEntityUtil.setUpdateBaseProperties(institution, user);
                Integer update = factory.getMapper(InstitutionFileMapper.class).updateByPrimaryKey(institution);
                if (update > 0) {
                    if (null != keepAddressList && keepAddressList.size() > 0) {
                        keepAddressList.forEach(url -> clientWrapper.deleteFile(url.split("#")[0]));
                    }
                    if (null != keepPreAddressList && keepPreAddressList.size() > 0) {
                        keepPreAddressList.forEach(url -> clientWrapper.deleteFile(url.split("#")[0]));
                    }
                }
            } else if (null != file && file.length > 0) {
                List<String> keepAddressList = new ArrayList<>();
                List<String> keepPreAddressList = new ArrayList<>();
                String originalFilename = null;
                if (file != null && file.length > 0) {
                    for (MultipartFile f : file) {
                        if (file != null) {
                            originalFilename = f.getOriginalFilename();
                            String url = clientWrapper.uploadFile(f);
                            String filPath = url + "#" + originalFilename;
                            keepAddressList.add(filPath);
                            String pdfPath = docConverterUtils.converterUpdate(f);
                            if (pdfPath != null) {
                                keepPreAddressList.add(pdfPath);
                            } else {
                                keepPreAddressList.add(filPath);
                            }
                        }
                    }
                }
                InstitutionFile institution = new InstitutionFile();
                institution.setAttachment((keepAddressList == null || keepAddressList.size() <= 0) ? null : new Gson().toJson(keepAddressList));
                institution.setPreviewAttachment((keepPreAddressList == null || keepPreAddressList.size() <= 0) ? null : new Gson().toJson(keepPreAddressList));
                institution.setCode(Tools.getCode32());
                institution.setCategoryId(category.getId());
                institution.setFileName(StringUtils.isNoneEmpty(institution.getFileName()) ? institution.getFileName() : originalFilename);
                institution.setInstitutionType(entity.getInstitutionType());
                institution.setCorpCode(category.getInstitutionType() == 1 ? null : corpCode);
                BaseEntityUtil.setAddBaseProperties(institution, user);
                Integer update = factory.getMapper(InstitutionFileMapper.class).insertSelective(institution);
            }
            factory.close();
            return msg;
        } catch (Exception e) {
            if (null != factory) {
                factory.close(false);
            }
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }
}
